package main

import (
	"flag"
	"fmt"
	"gitee.com/Cookie_XiaoD/go-terminalserver/client"
	"gitee.com/Cookie_XiaoD/go-terminalserver/config"
	"gitee.com/Cookie_XiaoD/go-terminalserver/util"
	"log"
	"net"
	"time"
)

func main() {
	initArgs()
	log.Println("车载终端网关启动中...")
	readCfg()
	start()

	for {
		time.Sleep(1 * time.Second)
	}

}

func initArgs() {
	//启动服务的时候，通常是 server -config 配置文件路径
	//没法配置成--config的方式
	//通过server -h或--help可以查看帮助
	flag.StringVar(&cfgPath, "config", "./server.cfg", "通过-config指定配置文件")
	flag.Parse()
}

func start() {
	addrStr := fmt.Sprintf("0.0.0.0:%v", G_Cfg.ServerPort)
	log.Printf("tcp监听地址：%v", addrStr)
	addr, err := net.ResolveTCPAddr("tcp", addrStr)
	if err != nil {
		log.Fatalf("监听地址有误:%v", err.Error())
	}
	for {
		startListen(addr)
		//如果接收终端连接异常，则5秒后重新开始监听
		time.Sleep(5 * time.Second)
	}
}

func startListen(addr *net.TCPAddr) {
	if G_Listener != nil {
		G_Listener.Close()
		G_Listener = nil
	}
	G_Listener, err := net.ListenTCP("tcp", addr)
	if err != nil {
		log.Fatalf("监听失败：%v", err.Error())
	}
	defer G_Listener.Close()
	for {
		log.Println("准备接收终端连接")
		conn, err := G_Listener.AcceptTCP()
		if err != nil {
			log.Println("监听客户端连接异常：%v", err.Error())
			break
		}
		log.Println("接收到客户端连接:", conn.RemoteAddr().String())
		clientCount++
		log.Printf("第%v个客户端", clientCount)
		var tc = client.NewTerminalClient(conn)
		//每个客户端，采用一个协程处理
		go tc.StartHandleUpData()
	}
}

func readCfg() {
	log.Println("读取配置文件...")
	cfgBytes, err := util.ReadAllFile(cfgPath)
	if err != nil {
		log.Fatalf("读取配置文件异常%v", err.Error())
	}
	cfg, err := config.InitCfg(cfgBytes)
	if err != nil {
		log.Fatalf("读取配置文件异常%v", err.Error())
	}
	G_Cfg = cfg
}

//网关全局配置
var cfgPath string
var G_Cfg *config.ServerCfg
var G_Listener *net.TCPListener
var clientCount uint64
